<template>
	<view class="shop_cart_content">
        <view class="shop_header">
            <scroll-view style="height: 100%;" scroll-y="true">
                <view  class="card_content" v-for="(item, index) in cartList_Gx" :key="index">
                    <view class="card_title">
                        <checkbox-group>
                            <label class="title_flex" @click="change_row_check(item, index)">
                                <checkbox :value="item.main.huohao" :checked="item.itemCheck" />
                                <view style="margin-right: 20rpx;">{{ item.main.huohaoname || '' }}</view>
                                <view>{{ item.main.pm || '' }}</view>
                            </label>
                        </checkbox-group>

                        <view class="title_flex" style="flex: 1; justify-content: center;">
                            <view class="title_flex">
                                <view>合计数量：</view> 
                                <view>{{ item.hjsl.toFixed(0) || 0 }}</view>
                            </view>
                            <view class="title_flex" style="margin-left: 20rpx;">
                                <view>合计价格：</view>
                                <view>￥ {{ item.hjPrice.toFixed(2) || 0 }}</view>
                            </view>
                        </view>

                        <view class="title_flex">
                            <button :plain="true" hover-class="hover_remove" @click="delRow(item, index)"> 移除 </button>
                        </view>
                    </view>
                    <!--  -->
                    <view v-for="(i, j) in item.colorList" :key="j">
                        <uni-swipe-action-item  v-for="(x, y) in i.chimaList" :key="y" :autoClose="false" :right-options="options" @click="delShop( x, y)" v-if="x.num" >
                            <view class="card_item" >
                                <checkbox-group @click="change_item_check(x, y)">
                                    <label class="cart_img">
                                        <checkbox :value="x.chima + x.color" :checked="x.check" />
                                        <view style="width: 100rpx; height: 100rpx;">
                                            <image style="height: 100%; width: 100%; border-radius: 10rpx;" :src="i.color_img || ''" />
                                        </view>
                                    </label>
                                </checkbox-group>

                                <view class="card_info">
                                    <view class="info_flex" style="margin-bottom: 5rpx;">{{ item.main.pm || '' }}</view>
                                    <view class="info_flex" style="flex: 1; align-items: flex-start;">
                                        <view class="info_flex" >
                                            <view>颜色：</view>
                                            <view>{{ x.color || '' }}</view>
                                        </view>
                                        <view class="info_flex" style="margin-left: 30rpx;">
                                            <view>尺码：</view>
                                            <view>{{ x.chima || '' }}</view>
                                        </view>
                                    </view>

                                    <view class="info_flex">
                                        <view class="info_flex" style="flex: 1;">
                                            <view>价格：</view>
                                            <view>￥ {{ item.main.xsprice.toFixed(2) || '' }}</view>
                                        </view>

                                        <view>
                                            <u-number-box 
                                                integer :min="1"
                                                inputWidth="90" 
                                                buttonSize="40"
                                                v-model="x.num"
                                                @change="valChange($event, x, y)"
                                                ></u-number-box>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </uni-swipe-action-item>
                    </view>


                    <!--  -->
                    
                    <!--  -->
                </view>
            </scroll-view>
        </view>

        <!-- 底部结算 -->
        <view class="shop_footer">
            <checkbox-group @click="change_all_check">
                <label class="title_flex">
                    <checkbox value="cb" :checked="selectAll" /> 全选
                </label>
            </checkbox-group>
           
            <view class="shop_account" >
                已选
                <text @click="handleA">{{ gxSl.toFixed(0) || 0 }}</text>
                款/
                <text>{{ totalSl.toFixed(0) || 0 }}</text>
                件, 合计
                <text>￥ {{ totalPrice.toFixed(2) || 0 }}</text>
            </view>

            <view>
                <button hover-class="hover_btn" @click="placOrder">确认下单</button>
            </view>
        </view>
	</view>
</template>

<script>
import customHeader from "@/components/custom-header/custom-header.vue";
import { mapState, mapMutations, mapGetters } from 'vuex';
	export default {
		components: {
			customHeader,
		},
		data() {
			return {
                options: [{
                    text: '删除',
                    style: {
                        backgroundColor: '#fb1904'
                    }
                }],
                selectAll: false,
                totalPrice: 0,
                totalSl: 0,
                gxSl: 0,
                lastTap: 0, // 记录上一次点击的时间戳 双击事件
			}
		},
        computed: {
            ...mapGetters(['cartList_Gx']),
        },
        watch: {
            cartList_Gx: {
                handler(newVal, oldVal) {
                    if (newVal.length == 0) {
                        this.selectAll = false
                    } else {
                        this.selectAll = newVal.every(i => i.itemCheck === true)
                    }
                    let b = this.calculateTotal(newVal)
                    this.totalPrice = b.totalPrice
                    this.totalSl = b.totalSl
                    this.gxSl = b.ksSl
                },
                deep: true,
                immediate: true,
            }
        },
       
		created() {},
		methods: {
            placOrder() {
                this.$emit('childPlacOrder', { gxSl: this.gxSl, totalSl: this.totalSl, totalPrice: this.totalPrice })
            },
            handleA() {
                let LoginType = uni.getStorageSync('loginData').LoginType
                const currentTime = new Date().getTime(); // 获取当前点击的时间戳
                const timeDifference = currentTime - this.lastTap; // 计算两次点击的时间差

                if (timeDifference < 300 && timeDifference > 0) { // 300ms以内为双击
                    uni.removeStorageSync(`${LoginType}Cart`)
                    let list = uni.getStorageSync(`${LoginType}Cart`)
                    console.log('== 删除缓存中的数据 ', list)
                    console.log('== 缓存中数据 ', list)
                }
                this.lastTap = currentTime; // 更新最后一次点击的时间戳
            },

            // 修改 input 数据
            valChange(e, item, index) {
                console.log('ee ', e.value, ' = ', index )
                let val = Number(e.value) || 0
                let c = this.updateStock(this.cartList_Gx, item, val)
                this.addCart_x(c)
            },

            delShop(item, index,) { // 还需要更新缓存中的数据
                console.log('== item 222  ', item)
                let b = this.deleteItem(this.cartList_Gx, item)
                this.addCart_x(b)
            },
            // 删除一类
            delRow(item, index) {
                console.log('== item row ', item)
                
                let _this = this

                uni.showModal({
                    title: '提示',
                    content: `确定要删除${item.main.huohaoname}吗`,
                    success: function (res) {
                        if (res.confirm) {
                            let c = _this.cartList_Gx.filter(i => i.main.huohao != item.main.huohao)
                            _this.addCart_x(c)
                        }
                    }
                });
            },


            // 勾选 或者 取消 某一项的 checkbox
            change_row_check(item, index) {
                console.log('== item ', item)
                let a = this.cartList_Gx.map(i => ({ 
                    ...i, 
                    itemCheck: item.main.huohao == i.main.huohao ? !i.itemCheck : i.itemCheck ,
                    colorList: i.colorList.map(j => ({
                        ...j,
                        chimaList: j.chimaList.map(k => ({
                            ...k,
                            // check: item.main.huohao == i.main.huohao ? !item.itemCheck : k.check
                            check: item.main.huohao == i.main.huohao ? !item.itemCheck : k.num == 0? true : k.check
                        }))
                    }))
                }))
                console.log('== a ', a)
                this.addCart_x(a)

            },
            // 单个勾选
            change_item_check(item, index) {
                console.log('== i ', index , ' == ', item)
                let z = this.updateCheckStatusAndItemCheck(this.cartList_Gx, item)

                console.log('== z ', z)
                this.addCart_x(z)
            },

            // 全选
            change_all_check() {
                this.selectAll = !this.selectAll
                console.log('== 全选 按钮 ', this.selectAll)
                let d  = this.cartList_Gx.map(i => ({ 
                        ...i, 
                        itemCheck: this.selectAll,
                        colorList: i.colorList.map(j => ({
                            ...j,
                            chimaList: j.chimaList.map(k => ({
                                ...k,
                                check: this.selectAll
                            }))
                    }))
                }))
                this.addCart_x(d)
            },


            // 函数 =======

            // 底部计算 合计 
            calculateTotal(arr) {
                let totalPrice = 0;
                let totalSl = 0;
                let ksSl = 0;

                // 遍历 arr 数组
                arr.forEach(item => {
                    // 获取当前 item 的 xsprice
                    const xsprice = item.main.xsprice;

                    // 遍历 colorList 数组
                    item.colorList.forEach(colorItem => {
                        // 遍历 chimaList 数组
                        colorItem.chimaList.forEach(chima => {
                            // 如果 check 为 true，计算 num * xsprice
                            if (chima.check) {
                                totalPrice += chima.num * xsprice;
                                totalSl += chima.num;
                                if (chima.num > 0) {
                                    ksSl ++
                                }
                            }
                        });
                    });

                    item.hjsl = item.colorList.map(i => {
                        return {
                            ...i,
                            num: i.chimaList.filter(j => j.check).reduce((total, color) => total + color.num, 0)
                        }
                    }).reduce((total, color) => total + color.num, 0)

                    item.hjPrice = item.hjsl * item.main.xsprice;

                });

                // 返回最终的总和
                return {totalPrice, totalSl, ksSl};
            },
            updateStock(arr, obj, sl) {
                arr.forEach(item => {
                    // 遍历 colorList
                    item.colorList.forEach(colorItem => {
                        // 遍历 colorItem.chimaList
                        colorItem.chimaList.forEach(chimaItem => {
                            // 检查 chimaItem 是否与 obj 匹配
                            if (
                                chimaItem.huohao === obj.huohao &&
                                chimaItem.chima === obj.chima &&
                                chimaItem.color === obj.color
                            ) {
                                // 更新 chimaItem.num
                                chimaItem.num = sl;

                                // 更新 colorList 的 num（计算 chimaList 中所有 num 的总和）
                                colorItem.num = colorItem.chimaList.reduce((sum, chima) => sum + chima.num, 0);
                            }
                        });
                    });

                    // 更新 hjsl（colorList 中所有 num 的总和）
                    item.hjsl = item.colorList.reduce((total, color) => total + color.num, 0);

                    // 更新 hjPrice（hjsl * xsprice）
                    item.hjPrice = item.hjsl * item.main.xsprice;
                });

                return arr;
            },


            // 单个勾选组件
            updateCheckStatusAndItemCheck(arr, obj) {
                arr.forEach(item => {
                    let allChimaList = []
                    item.colorList.forEach(colorItem => {
                        colorItem.chimaList.forEach(chimaItem => {
                            chimaItem.check = chimaItem.num == 0 ? true : chimaItem.check
                            allChimaList.push(chimaItem)
                            // 检查 chimaItem 是否与 obj 匹配
                            if (chimaItem.huohao === obj.huohao &&
                                chimaItem.chima === obj.chima &&
                                chimaItem.color === obj.color &&
                                chimaItem.num === obj.num) {
                                // 如果匹配，更新 check 状态
                                chimaItem.check = !obj.check;
                            }
                        });
                    });

                    let a = allChimaList.every(i => i.check === true)
                    item.itemCheck = a
                });

                return arr;
            },



            // 删除 某一项
            deleteItem(arr, obj) {
                arr.forEach(item => {
                    // 遍历 colorList
                    item.colorList.forEach(colorItem => {
                        // 遍历 colorItem.chimaList
                        colorItem.chimaList = colorItem.chimaList.filter(chimaItem => {
                            // 检查是否匹配
                            if (
                                chimaItem.huohao === obj.huohao &&
                                chimaItem.chima === obj.chima &&
                                chimaItem.color === obj.color
                            ) {
                                // 如果匹配，删除该项，返回 false
                                return false;
                            }
                            return true; // 如果不匹配，保留该项
                        });

                        // 更新 colorList.num（重新计算该颜色下所有 chimaList.num 的和）
                        colorItem.num = colorItem.chimaList.reduce((sum, chima) => sum + chima.num, 0);
                    });

                    item.colorList = item.colorList.filter( i => i.chimaList.length)

                    // 更新 hjsl（colorList 中所有 num 的和）
                    item.hjsl = item.colorList.reduce((total, color) => total + color.num, 0);

                    // 更新 hjPrice（hjsl * xsprice）
                    item.hjPrice = item.hjsl * item.main.xsprice;
                });

                // 删除 colorList 为空的对象
                let a = arr.filter(item => item.hjsl)
                return a;
            },
            ...mapMutations([
                "addCart_x",
            ]),
		},
        onHide() {
            console.log('== onHide 购物车组件 同步 数据 --11')
        },
	}
</script>

<style lang="less" scoped>
.shop_cart_content {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;
    font-size: 16rpx;

    .shop_header {
        flex: 1;
        margin-top: 5rpx;
        overflow: auto;
        background: #f5f5f5;

        .card_content {
            padding: 5rpx 5rpx 10rpx 5rpx;
            background: #fff;
            margin-bottom: 10rpx;

            .card_title {
                display: flex;
                align-items: center;
                padding: 10rpx 5rpx;
                border-bottom: 3rpx dashed #ccc;

                .title_flex {
                    display: flex;
                    align-items: center;

                    button {
                        color: #ffac60;
                        border: 1rpx solid #ffac60;
                        width: 100rpx;
                    }
                    .hover_remove {
                        background: #dfdede;
                    }
                } 
            }  
        }

       

        .card_item {
            height: 100rpx;
            display: flex;
            padding: 10rpx 0;
            border-bottom: 1rpx dashed #ccc;


            .cart_img {
                display: flex;
                align-items: center;
            }

            .card_info {
                padding: 5rpx 5rpx 5rpx 20rpx;
                flex: 1;
                display: flex;
                flex-direction: column;

                .info_flex {
                    display: flex;
                    align-items: center;
                }
            }
        }
    }

    .shop_footer {
        display: flex;
        align-items: center;
        background: #fff;
        padding: 10rpx 20rpx;
        border-top: 1rpx solid #ccc;
        font-size: 20rpx;

        .shop_account {
            flex: 1;
            text-align: center;

            text {
                color: #ffac60;
                padding: 0 10rpx;
            }
           
        }
        button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 120rpx;
            background: #ffac60;
            color: #fff;
            margin: 0;
        }
        .hover_btn {
            background: #e49a55;
        }
    }

}
</style>
